<?php
	//ini_set("display_errors","Off");
	class DBhandler {
		//single instance of DBhandler object
		private static $instance;
		
		private function DBhandler() { //loads variables from file to get access to database
			if (file_exists('../services/config.php')) {
				require('../services/config.php');
			}
			else  if (file_exists('services/config.php')) {
				require('services/config.php');
			}
			
			$this->server = $iserver; //mysql server address
			$this->username = $iusername; //mysql login username
			$this->password = $ipassword; //mysql login password
			$this->database = $idatabase; //select the database in mysql
			$this->connect();
		}
		
		public static function getInst() {
			if (!self::$instance) {
				self::$instance = new DBhandler();
			}
			return self::$instance;
		}
		
		public function connect() { //connects to mysql server 
			$this->connectionResult = mysql_connect($this->server, $this->username, $this->password);
			if ($this->connectionResult) { //after successful connect we select our database
				$this->selectedDB = mysql_select_db($this->database, $this->connectionResult); //selecting database that was set in config.php
				$this->query('set names utf8'); //set correct collation for connection
				return $this->selectedDB;
			}
			else {
				return $this->connectionResult;
			}
		}
		
		public function query($query) {
			$this->queryHandler = mysql_query($query); //run query
			return $this->queryHandler; //save to object and return
		}
		
		public function cui($length = 32) { //creates some unique id
			$uniqueId = substr(md5(uniqid(rand(), true)), 0, $length);
			return $uniqueId;
		}
		
		public function get() { //getting each row from result to associative array
			$array = array(); //new array
			while ($row = mysql_fetch_assoc($this->queryHandler)) { //for each row in result of query creates associative array
				array_push($array, $row); //push row (associative array) into array
			}
			return $array; 
		}
		
		public function close() { //closes connection to database
			$this->closed = mysql_close($this->connectionResult);
			return $this->closed;
		}
		
		public function rmInject($input) {
			return mysql_real_escape_string($input);
		}
		
		public function error() {
			return mysql_error();
		}
	}
	
	//testing
	/*
	$dbHandler = new DBhandler();
	$dbHandler->connect();
	$str = "''or''=''";
	echo mysql_real_escape_string($str);
	$dbHandler->query("select * from USERS where 1");
	$ar = $dbHandler->get();
	print_r($ar);
	var_dump($dbHandler->connectionResult);
	$dbHandler->close();*/
?>